const { sequelize } = require("../db/index")
const { DataTypes, Model } = require("sequelize")
const User = require("./user_model")
const Cleaner = require("./cleaner_model")
const moment = require("moment")

class GoodsStock extends Model {

  static async createGoodsStock({
    sku_id,
    store_house_id,
    stock,
    price,
    cost_price
  }) {
    const result = await GoodsStock.findOrCreate({
      where: { sku_id, store_house_id },
      default: {
        sku_id,
        store_house_id,
        stock,
        price,
        cost_price
      }
    })
    // const goods = await Goods.create({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
    return result
  }

  static async addAdmin(buildingId, userId) {
    try {
      const cate = await Cate.findOne({ where: { id: buildingId } })
      const user = await User.findOne({ where: { id: userId } })
      const result = await cate.addAdmin(user)
      return result
    } catch (e) {
      throw new Error("已存在该管理员，添加失败")
    }
  }
  static async addCleaner(buildingId, cleanerId) {
    try {
      const cleaner = await Cleaner.findOne({ where: { id: cleanerId } })
      cleaner.buildingId = buildingId
      return await cleaner.save()
    } catch (e) {
      throw new Error("添加保洁员失败")
    }
  }
  static async addFloor(buildingId, floor) {
    try {
      floor.buildingId = buildingId
      return await floor.save()
    } catch (error) {
      console.log(error)
    }
  }
}

GoodsStock.init(
  {
    sku_id: {
      comment: "商品规格ID",
      type: DataTypes.INTEGER,
      primaryKey: true,
      // unique: "stockUnique",
      unique: true,
      allowNull: false
    },
    store_house_id: {
      comment: "仓库ID",
      type: DataTypes.INTEGER,
      primaryKey: true,
      // unique: "stockUnique",
      unique: true,
      allowNull: false
    },
    stock: {
      comment: "库存",
      type: DataTypes.INTEGER,
      allowNull: false
    },
    price: {
      comment: "价格",
      type: DataTypes.INTEGER,
      autoIncrement: false,
      allowNull: false
    },
    cost_price: {
      comment: "成本价格",
      type: DataTypes.INTEGER,
      autoIncrement: false,
      allowNull: false
    },
    update_time: {
      comment: "更新时间",
      type: DataTypes.STRING,
      get() {
        return moment(this.getDataValue("update_time")).format(
          "YYYY-MM-DD HH:mm:ss"
        )
      }
    }
  },
  {
    sequelize,
    modelName: "sp_store_goods_stock",
    freezeTableName: true,
    paranoid: false,
    timestamps: false,
    // indexes: [
    //   {
    //     name: 'stockUnique',
    //     unique: true,
    //     fields: ['sku_id', 'store_house_id']
    //   }
    // ]
  }
)

GoodsStock.removeAttribute("id")

module.exports = GoodsStock
